<!DOCTYPE html>
<html lang="zh" xmlns:th="http://www.thymeleaf.org">
<head>
    <th:block th:include="include :: header('新增模型')"/>
    <!-- 引入 Font Awesome 的 CSS -->
    <link rel="stylesheet" href="/fontawesome-free-6.4.0-web/css/all.min.css">


<!--    &lt;!&ndash; 引入 SweetAlert2 CSS &ndash;&gt;-->
<!--    <link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/sweetalert2@10/dist/sweetalert2.min.css">-->

<!--    &lt;!&ndash; 引入 SweetAlert2 JS &ndash;&gt;-->
<!--    <script src="https://cdn.jsdelivr.net/npm/sweetalert2@10"></script>-->
    <script src="/sweetalert2-11.12.2/sweetalert2@11.js"></script>
</head>
<body class="white-bg">
<div class="wrapper wrapper-content animated fadeInRight ibox-content">
    <form class="form-horizontal m" id="form-model-add">
        <div class="form-group">
            <label class="col-sm-3 control-label">模型名称：</label>
            <div class="col-sm-8">
                <input id="modelName" name="modelName" class="form-control" type="text">
            </div>
        </div>
        <div class="form-group">
            <label class="col-sm-3 control-label">适用图像高：</label>
            <div class="col-sm-8">
                <input id="fitHeight" name="fitHeight" class="form-control" type="text">
            </div>
        </div>
        <div class="form-group">
            <label class="col-sm-3 control-label">适用图像宽：</label>
            <div class="col-sm-8">
                <input id="fitWidth" name="fitWidth" class="form-control" type="text">
            </div>
        </div>
        <div class="form-group">
            <label class="col-sm-3 control-label">输入通道数：</label>
            <div class="col-sm-8">
                <input id="inputChannel" name="inputChannel" class="form-control" type="text">
            </div>
        </div>
        <div class="form-group">
            <label class="col-sm-3 control-label">输出通道数：</label>
            <div class="col-sm-8">
                <input id="outputChannel" name="outputChannel" class="form-control" type="text">
            </div>
        </div>
        <!--			<div class="form-group">	-->
        <!--				<label class="col-sm-3 control-label">上传时间：</label>-->
        <!--				<div class="col-sm-8">-->
        <!--					<input id="uploadTime" name="uploadTime" class="form-control" type="text">-->
        <!--				</div>-->
        <!--			</div>-->
        <!--			<div class="form-group">	-->
        <!--				<label class="col-sm-3 control-label">归属用户：</label>-->
        <!--				<div class="col-sm-8">-->
        <!--					<input id="userId" name="userId" class="form-control" type="text">-->
        <!--				</div>-->
        <!--			</div>-->
        <!--			<div class="form-group">	-->
        <!--				<label class="col-sm-3 control-label">模型位置：</label>-->
        <!--				<div class="col-sm-8">-->
        <!--					<input id="location" name="location" class="form-control" type="text">-->
        <!--				</div>-->
        <!--			</div>-->

        <!-- 添加是否公开的选项 -->
        <div class="form-group">
            <label class="col-sm-3 control-label">是否公开：</label>
            <div class="col-sm-8">
                <input type="radio" id="public-yes" name="is-public" value="yes">
                <label for="public-yes" style="margin-right: 10px;">是</label>
                <input type="radio" id="public-no" name="is-public" value="no" checked>
                <label for="public-no">否</label>
            </div>
        </div>

        <div class="form-group">
            <label class="col-sm-3 control-label">上传模型：</label>
            <div class="col-sm-8">
                <!--                只能上传一个文件 -->
                <input id="model-upload" type="file" accept=".py">
                <!--                <input id="model-upload" type="file" accept=".py" multiple>-->
                <!--                <span id="image-count" class="help-block">上传的图片数量：0</span>-->
            </div>
        </div>

        <div class="form-group">
            <label class="col-sm-3 control-label">上传权重（可选）：</label>
            <div class="col-sm-8">
                <input id="weight-upload" type="file" accept=".pth">
            </div>
        </div>
    </form>
</div>
<div th:include="include::footer"></div>
<script type="text/javascript">
    console.log('model-add.html')
    var prefix = ctx + "deep_learning/model"
    $("#form-model-add").validate({
        rules: {
            xxxx: {
                required: true,
            },
        },
        focusCleanup: true
    });

    function submitHandler() {
        var modelName = $('#modelName').val();
        $.ajax({
            url: prefix + "/checkModelNameUnique",
            type: "GET",
            data: { name: modelName },
            success: function(response) {
                if (response) {
                    Swal.fire({
                        icon: 'error',
                        title: '错误',
                        text: '名称已存在，请使用其他名称',
                        showConfirmButton: true,
                        allowOutsideClick: false,
                        allowEscapeKey: false
                    });
                } else {
                    if ($.validate.form()
                        && $('#model-upload')[0].files.length > 0
                        //     各项不能为空，长宽合法，输入输出通道合法
                        // 正则表达式验证
                        && /^[0-9]+$/.test($('#fitHeight').val())
                        && /^[0-9]+$/.test($('#fitWidth').val())
                        && /^[0-9]+$/.test($('#inputChannel').val())
                        && /^[0-9]+$/.test($('#outputChannel').val())
                        && $('#modelName').val()
                    ) {
                        // 获取表单数据
                        var formData = new FormData();
                        // formData.append('id', $('#id').val())
                        formData.append('modelName', $('#modelName').val());
                        formData.append('fitHeight', $('#fitHeight').val());
                        formData.append('fitWidth', $('#fitWidth').val());
                        formData.append('inputChannel', $('#inputChannel').val());
                        formData.append('outputChannel', $('#outputChannel').val());
                        // 获取是否公开的选项
                        var isPublicValue = $("input[name='is-public']:checked").val();
                        // 如果是公开的，则将 isPublicValue 置为 1，否则置为 0
                        if (isPublicValue == 'yes') {
                            isPublicValue = 1;
                        } else {
                            isPublicValue = 0;
                        }
                        formData.append('isPublic', isPublicValue);
                        //     发送选中文件给后端，只能上传一个文件
                        formData.append('file', $('#model-upload')[0].files[0]);
                        formData.append('weightFile', $('#weight-upload')[0].files[0]);
                        // formData.append('files', $('#model-upload')[0].files);
                        $.ajax({
                            url: prefix + '/uploadModel', // 后端控制器的请求路径
                            type: 'POST',
                            data: formData,
                            processData: false,
                            contentType: false,
                            success: function (response) {
                                Swal.fire({
                                    icon: 'success',
                                    title: '文件上传成功',
                                    showConfirmButton: false,
                                    timer: 1500
                                }).then(function () {
                                    // console.log("发送消息给model.html页面，让它刷新数据表格")
                                    window.parent.postMessage('refreshTable', '*');
                                    // 关闭当前弹窗
                                    $('#form-model-add').serialize()   //
                                    $.modal.close();

                                });
                                console.log("文件信息", response);

                            },
                            error: function (xhr, status, error) {
                                Swal.fire({
                                    icon: 'error',
                                    title: '文件上传失败',
                                    text: '错误信息: ' + error,
                                    showConfirmButton: false,
                                    timer: 2000
                                });
                                console.error('请求失败:', error);
                            }
                        });
                        // $.operate.save(prefix + "/add", $('#form-model-add').serialize());
                    }
                    //     表单验证失败的提醒
                    else {
                        $.modal.alert("表单验证失败，请检查输入项！");
                    }
                }
            },
            error: function(xhr, status, error) {
                Swal.fire({
                    icon: 'error',
                    title: '请求失败',
                    text: '检查任务名称失败，请稍后重试',
                    showConfirmButton: true,
                    allowOutsideClick: false,
                    allowEscapeKey: false
                });
            }
        });

        window.parent.postMessage('refreshTable', '*');
    }
</script>
</body>
</html>
